﻿using SAD_Assignment1.BLO;
using SAD_Assignment1.DTO;
using SAD_Assignment1.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SAD_Assignment1.Public
{
    public partial class Login : System.Web.UI.Page
    {
        private string redirect = Resource.Home;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Params["redirect"] != null)
            {
                redirect = Request.Params["redirect"];
            }
            if (Request.Params["logout"] != null)
            {
                Logout();
            }
            if (Session["account"] != null)
            {
                Response.Redirect(Resource.Home);
            }
            Form.DefaultButton = LoginBtn.UniqueID;
        }

        protected void LoginBtn_Command(object sender, CommandEventArgs e)
        {
            string email = txtEmail.Text;
            string password = txtPassword.Text;
            AccountBLO accBLO = new AccountBLO();
            bool success = accBLO.CheckLogin(email, password);
            if (success)
            {
                AccountDTO accDTO = accBLO.getAccountInfo(email);
                if ("deactive".Equals(accDTO.Roles))
                {
                    Response.Redirect(Resource.Info + "?msgID=1");
                    return;
                }
                else if ("block".Equals(accDTO.Roles))
                {
                    Response.Redirect(Resource.Info + "?msgID=4");
                    return;
                }
                else
                {
                    Session["account"] = accDTO;
                    Response.Redirect(redirect);
                }
            }
            txtError.Text = "Email hoặc mật khẩu không chính xác";            
        }

        protected void Logout()
        {
            Session.Clear();            
            Response.Redirect(Resource.Home);
        }
    }
}